package com.ruoyi.web.controller.module.estate;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Random;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.*;
import com.ruoyi.system.domain.module.event.*;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.estate.*;
import com.ruoyi.system.service.module.wx.IWxTemplateService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 报修记录Controller
 *
 * @author ruoyi
 * @date 2021-08-24
 */
@Validated
@Api(value = "报修记录控制器", tags = {"报修记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/repair/record")
public class RepairRecordController extends BaseController {

    private final IRepairRecordService repairRecordService;
	private final IRepairRecordImgService repairRecordImgService;
//	private final IWorkerService workerService;
    private final IEstateService estateService;
	private final IEstateUserService estateUserService;
	private final ISysUserService sysUserService;
    private final IWxUserService wxUserService;
	private final IWxTemplateService wxTemplateService;
	private final IEstateRoomService estateRoomService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

    /**
     * 查询报修记录列表
     */
    @ApiOperation("查询报修记录列表")
    @PreAuthorize("@ss.hasPermi('module:repairrecord:list')")
    @GetMapping("/list")
    public TableDataInfo<RepairRecord> list(@Validated RepairRecord repairRecord) {
        SysUser sysUser = getUser();
        QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        }else{
			if(repairRecord.getEstateId()!= null){
				qw.eq("estate_id",repairRecord.getEstateId());
			}
		}
        if(StrUtil.isNotEmpty(repairRecord.getPhoneNum())){
			qw.eq("phone_num",repairRecord.getPhoneNum());
		}


		if(repairRecord.getRecordType() !=null){
			qw.eq("record_type",repairRecord.getRecordType());
		}
		if(repairRecord.getRoomNo() !=null){
			qw.like("room_no",repairRecord.getRoomNo());
		}

		if(repairRecord.getState() !=null && repairRecord.getState()!=3){
			qw.eq("state",repairRecord.getState());
			qw.eq("is_del",0);
		}else if (repairRecord.getState() == 3){
			qw.eq("is_del",1);
		}
		if (repairRecord.getBeginDate()!=null){
			qw.between("create_time",repairRecord.getBeginDate() + " 00:00:00",repairRecord.getEndDate() + " 23:59:59");
		}
        qw.orderByDesc("create_time");
        TableDataInfo<RepairRecord> td = PageUtils.buildDataInfo(repairRecordService.page(PageUtils.buildPage(),qw));
        List<RepairRecord> list = td.getRows();
        list.forEach(repairRecord1 -> {
			List<String> imgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordImg = new QueryWrapper<>();
			qwRecordImg.eq("record_id",repairRecord.getId());
			qwRecordImg.eq("img_type", 0);
			List<RepairRecordImg> recordImgs = repairRecordImgService.list(qwRecordImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordImgs){
					imgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord1.setImgUrlList(imgUrls);
			}
			List<String> opImgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordOpImg = new QueryWrapper<>();
			qwRecordOpImg.eq("record_id",repairRecord.getId());
			qwRecordOpImg.eq("img_type", 1);
			List<RepairRecordImg> recordOpImgs = repairRecordImgService.list(qwRecordOpImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordOpImgs){
					opImgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord1.setOpImgUrlList(opImgUrls);
			}

            WxUser wxUser = wxUserService.findById(repairRecord1.getUserId());
            if(wxUser != null){
                repairRecord1.setNickName(EmojiUtil.toUnicode(wxUser.getNickName()));
            }
        });
        return td;
    }

	@ApiOperation("查询报修记录列表")
	@PreAuthorize("@ss.hasPermi('module:repairrecord:list')")
	@GetMapping("/num")
	public List<Integer> num(@Validated RepairRecord repairRecord) {
		SysUser sysUser = getUser();
		QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(repairRecord.getEstateId()!= null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		}
		if(StrUtil.isNotEmpty(repairRecord.getPhoneNum())){
			qw.eq("phone_num",repairRecord.getPhoneNum());
		}
		if(repairRecord.getState() !=null){
			qw.eq("state",repairRecord.getState());
		}
		qw.orderByDesc("create_time");
		List<RepairRecord> list = repairRecordService.list(qw);
		List<Integer> integers = new ArrayList<>();
		int yichuli = 0;
		int weichuli = 0;
		for (RepairRecord list1 : list){
			if(list1.getState()==2||list1.getState()==3){
				yichuli+=1;
			}else {
				weichuli+=1;
			}
		}
		integers.add(yichuli);
		integers.add(weichuli);
		return integers;
	}





    /**
     * 导出报修记录列表
     */
    @ApiOperation("导出报修记录列表")
    @PreAuthorize("@ss.hasPermi('module:repairrecord:export')")
    @Log(title = "报修记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<RepairRecord> export(@Validated RepairRecord repairRecord) {
		SysUser sysUser = getUser();
		QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(repairRecord.getEstateId()!= null){
				qw.eq("estate_id",repairRecord.getEstateId());
			}
		}
		if(StrUtil.isNotEmpty(repairRecord.getPhoneNum())){
			qw.eq("phone_num",repairRecord.getPhoneNum());
		}


		if(repairRecord.getRecordType() !=null){
			qw.eq("record_type",repairRecord.getRecordType());
		}
		if(repairRecord.getRoomNo() !=null){
			qw.like("room_no",repairRecord.getRoomNo());
		}
		if (repairRecord.getBeginDate()!=null){
			qw.between("create_time",repairRecord.getBeginDate() + " 00:00:00",repairRecord.getEndDate() + " 23:59:59");
		}
		if(repairRecord.getState() !=null && repairRecord.getState()!=3){
			qw.eq("state",repairRecord.getState());
			qw.eq("is_del",0);
		}else if (repairRecord.getState() == 3){
			qw.eq("is_del",1);
		}
		qw.orderByDesc("create_time");
        List<RepairRecord> list = repairRecordService.list(qw);
		for (RepairRecord list1:list){
			if (list1.getCreateTime() != null) {
				list1.setCreateTimes(DateUtils.getTime(list1.getCreateTime()));
			}
			if (list1.getOpTime() != null) {
				list1.setOpTimes(DateUtils.getTime(list1.getOpTime()));
			}
			WxUser wxUser = wxUserService.findById(list1.getUserId());
			if(wxUser != null){
				list1.setNickName(EmojiUtil.toUnicode(wxUser.getNickName()));
			}
		}
        ExcelUtil<RepairRecord> util = new ExcelUtil<RepairRecord>(RepairRecord.class);
        return util.exportExcel(list, "报修记录");
    }


	@ApiOperation("查询计划任务：人员计划记录列表")
	@PreAuthorize("@ss.hasPermi('module:planTask:list')")
	@GetMapping("/count")
	public EstateRepairCount count(@Validated RepairRecord repairRecord) {
		EstateRepairCount count = new EstateRepairCount();
		SysUser sysUser = getUser();
		QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(repairRecord.getPropertyId() != null){
				qw.eq("property_id",repairRecord.getPropertyId());
			}
			if(repairRecord.getEstateId() != null){
				qw.eq("estate_id",repairRecord.getEstateId());
			}
		}
		List<RepairRecord> RepairList = repairRecordService.list(qw);
		qw.ne("state",3);
		qw.groupBy("op_worker_id");
		List<RepairRecord> userList = repairRecordService.list(qw);
//		count.setPlanCount(taskList.size());
		count.setUserCount(userList.size());
		EventPlanUserCount eventPlanUserCount = new EventPlanUserCount();
		List<EstateRepairCountUser> userCountList = new ArrayList<>();

		List<EstateRepairCountInfo> yiwanchengListAll = new ArrayList<>();

		for (RepairRecord user:userList){
			List<EstateRepairCountInfo> yiwanchengs = new ArrayList<>();
			EstateRepairCountUser count1 = new EstateRepairCountUser();
			count1.setRealName(user.getOpWxNickName());
			int weiwancheng = 0;
			int jinxingzhong = 0;
			int yiwancheng = 0;
			int renwu = 0;
			for (RepairRecord task:RepairList){
				//总统计表
				//统计任务数
				if (user.getOpWxUserId()!=null&&task.getOpWxUserId()!=null){
					if (user.getOpWxUserId().equals(task.getOpWxUserId())){
						if (task.getState()==0){
							weiwancheng+=1;
						}
						if (task.getState()==1){
							jinxingzhong+=1;
						}
						if (task.getState()==2||task.getState()==3){
							yiwancheng+=1;
							renwu+=1;
							EstateRepairCountInfo info = new EstateRepairCountInfo();
							info.setPlanName(repairRecordService.findById(task.getId()).getContent());
							if (task.getOpWorkerId()!=null){
								SysUser user1 = sysUserService.selectUserById(Long.valueOf(task.getOpWorkerId()));
								if (user1!=null&&user1.getNickName()!=null){
									info.setRealName(user1.getNickName());
								}
							}
							info.setEndTime(task.getOpTime());
							yiwanchengs.add(info);
						}
					}
				}
			}
			for (EstateRepairCountInfo info:yiwanchengs){
				info.setCompleted(renwu);
				yiwanchengListAll.add(info);
			}
			count1.setBegan(weiwancheng);
			count1.setAfoot(jinxingzhong);
			count1.setCompleted(yiwancheng);
			count1.setCount(weiwancheng+yiwancheng+jinxingzhong);
			userCountList.add(count1);
		}
		count.setUserPlanInfoList(yiwanchengListAll);
		count.setUserPlanList(userCountList);
		int weiwancheng = 0;
		int yiwancheng = 0;
		int jinxingzhong = 0;
		QueryWrapper<RepairRecord> qwWeiwancheng = new QueryWrapper<>();
		qwWeiwancheng.eq("state",0);
		List<RepairRecord> weiwanchengList = repairRecordService.list(qwWeiwancheng);
		weiwancheng=weiwanchengList.size();

		QueryWrapper<RepairRecord> qwJinxingzhong = new QueryWrapper<>();
		qwJinxingzhong.eq("state",0);
		List<RepairRecord> jinxingzhongList = repairRecordService.list(qwJinxingzhong);
		jinxingzhong=jinxingzhongList.size();

		QueryWrapper<RepairRecord> qwYiwancheng = new QueryWrapper<>();
		qwYiwancheng.eq("state",2).or().eq("state",3);
		List<RepairRecord> yiwanchengList = repairRecordService.list(qwYiwancheng);
		yiwancheng=yiwanchengList.size();



		count.setBegan(weiwancheng);
		count.setAfoot(jinxingzhong);
		count.setCompleted(yiwancheng);
		count.setPlanCount(count.getCompleted()+count.getAfoot()+count.getBegan());
		return count;
	}



    /**
     * 获取报修记录详细信息
     */
    @ApiOperation("获取报修记录详细信息")
    @PreAuthorize("@ss.hasPermi('module:repairrecord:query')")
    @GetMapping("/{id}")
    public AjaxResult<RepairRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        RepairRecord repairRecord = repairRecordService.getById(id);
        if(repairRecord != null) {
			List<String> imgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordImg = new QueryWrapper<>();
			qwRecordImg.eq("record_id",repairRecord.getId());
			qwRecordImg.eq("img_type", 0);
			List<RepairRecordImg> recordImgs = repairRecordImgService.list(qwRecordImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordImgs){
					imgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord.setImgUrlList(imgUrls);
			}


			List<String> opImgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordOpImg = new QueryWrapper<>();
			qwRecordOpImg.eq("record_id",repairRecord.getId());
			qwRecordOpImg.eq("img_type", 1);
			List<RepairRecordImg> recordOpImgs = repairRecordImgService.list(qwRecordOpImg);
			if(CollUtil.isNotEmpty(recordOpImgs)){
				for (RepairRecordImg recordImg : recordOpImgs){
					opImgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord.setOpImgUrlList(opImgUrls);
			}

			WxUser wxUser = wxUserService.findById(repairRecord.getUserId());
			if(wxUser != null){
				repairRecord.setNickName(EmojiUtil.toUnicode(wxUser.getNickName()));
			}
		}
        return AjaxResult.success(repairRecord);
    }

    /**
     * 新增报修记录
     */
    @ApiOperation("新增报修记录")
    @PreAuthorize("@ss.hasPermi('module:repairrecord:add')")
    @Log(title = "报修记录", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody RepairRecord repairRecord) {
		if (repairRecord.getEstateId()!=null){
			Estate estate = estateService.findById(repairRecord.getEstateId());
			repairRecord.setEstateName(estate.getEstateName());
		}
		repairRecord.setUserId(0);
		repairRecord.setNickName("物业客服");
		Random random = new Random();
		int randomNumber = random.nextInt(1000000000);
		String randomString = String.valueOf(randomNumber);
		repairRecord.setRecordNo("R171"+randomString);
		if (repairRecord.getRoomNo()!=null){
			QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
			qw.eq("room_no",repairRecord.getRoomNo());
			qw.eq("estate_id",repairRecord.getEstateId());
			List<EstateRoom> rooms = estateRoomService.list(qw);
			if (rooms.size()>0){
				repairRecord.setPhoneNum(rooms.get(0).getPhoneNum());
			}
		}
		repairRecord.setPickType(1);
		repairRecord.setState(0);
		repairRecord.setOpState(0);
        return toAjax(repairRecordService.save(repairRecord) ? 1 : 0);
    }

	/**
	 * 批量新增报修记录
	 */
	@ApiOperation("新增报修记录")
	@PreAuthorize("@ss.hasPermi('module:repairrecord:addPiliang')")
	@Log(title = "报修记录", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping("/addPiliang")
	public AjaxResult<Void> addPiliang(@Validated(AddGroup.class) @RequestBody RepairRecord repairRecord) {
		if (repairRecord.getPropertyId()!=null){
			QueryWrapper<Estate> qw = new QueryWrapper<>();
			qw.eq("property_id",repairRecord.getPropertyId());
			List<Estate> estates = estateService.list(qw);
			for (Estate estate:estates){
				RepairRecord repair = new RepairRecord();
				repair.setId(null);
				repair.setEstateName(estate.getEstateName());
				repair.setUserId(0);
				repair.setEstateId(estate.getId());
				repair.setNickName("管理人员");
				repair.setPhoneNum("请联系管理人员");
				Random random = new Random();
				int randomNumber = random.nextInt(1000000000);
				String randomString = String.valueOf(randomNumber);
				repair.setRecordNo("R171"+randomString);
				repair.setPickType(1);
				repair.setState(0);
				repair.setOpState(0);
				repair.setPropertyId(repairRecord.getPropertyId());
				repair.setRoomNo(repairRecord.getRoomNo());
				repair.setContent(repairRecord.getContent());
				Boolean b = repairRecordService.save(repair);
				if (!b){
					return toAjax(0);
				}
			}
		}
		return toAjax(1);
	}
    /**
     * 修改报修记录
     */
    @ApiOperation("修改报修记录")
    @PreAuthorize("@ss.hasPermi('module:repairrecord:edit')")
    @Log(title = "报修记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody RepairRecord repairRecord) {
    	if(repairRecord.getOpWorkerId()!=null){
			EstateUser estateUser = estateUserService.getById(repairRecord.getOpWorkerId());
			if(estateUser != null){
				repairRecord.setState(1);
				repairRecord.setOpState(1);

				SysUser sysUser = sysUserService.selectUserById(estateUser.getSysUserId());
				if(sysUser != null){
					repairRecord.setOpUserName(sysUser.getNickName());
					repairRecord.setOpWorkerPhone(sysUser.getPhoneNum());
				}

				repairRecord.setOpWxUserId(estateUser.getUserId());
				repairRecord.setOpWxNickName(estateUser.getNickName());
			}
		}
    	boolean bl = repairRecordService.updateById(repairRecord);
    	if(bl){
			wxTemplateService.sendWxMsgRepair(repairRecord,1);
		}
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 删除报修记录
     */
    @ApiOperation("删除报修记录")
    @PreAuthorize("@ss.hasPermi('module:repairrecord:remove')")
    @Log(title = "报修记录" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(repairRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
